package com.dhh.activity;

import greendroid.app.GDActivity;
import greendroid.widget.ActionBarItem.Type;
import java.util.ArrayList;
import java.util.List;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import com.dhh.R;
import com.dhh.dao.DataBaseHelper;
import com.dhh.util.Constant;
import com.dhh.util.StringUtil;
import com.dhh.util.manager.FoodManager;
import com.dhh.vo.Food;
import com.dhh.widget.AmazingAdapter;
import com.dhh.widget.AmazingListView;

public class FoodAddActivity extends GDActivity implements View.OnClickListener {	
	AmazingListView lsComposer;
	SectionComposerAdapter adapter;
	private FoodManager fManager;
	private DataBaseHelper db;
	private ProgressDialog progressDialog;
	private String fActivity;
	private String did;
	private Button sButton;
	private Button addButton;
	private EditText fText;

	@Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        this.getIntent().getIntExtra("activity", 0);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setActionBarContentView(R.layout.foodsearch);
        
        db = new DataBaseHelper(getBaseContext());
        db.openDataBase();        
        fManager = new FoodManager(db);
        
        if(getIntent().getExtras()!=null){
            fActivity = getIntent().getExtras().getString(Constant.FROM_ACTIVITY);
            did = getIntent().getExtras().getString(Constant.C_DIET_ID); 
        }       
        
        
        initActionBar();
        initView();
        
        
	}
	
	@Override
	public void onStart() {
        super.onStart();   
	}
	
	@Override
    public void onResume(){
    	super.onResume();
        db.openDataBase();       
    }
    
    @Override
	protected void onPause(){
		super.onPause();
		if (db != null) {
			db.close();
		}
	}
    
    @Override
	protected void onStop(){
		super.onStop();
	}
	
	public void initActionBar(){
		getActionBar().setTitle("Food Search");
        getActionBar().setBackgroundColor(Color.rgb(14, 166, 249));
        getActionBar().getChildAt(0).
        	setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(FoodAddActivity.this,HomeActivity.class);	
					startActivity(intent);
				}});
        addActionBarItem(Type.Add).getItemView()
        .setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(FoodAddActivity.this, AddCustomFoodActivity.class);	
				startActivity(intent);
			}}); 
	}
	
	public void initView(){
		fText = (EditText) findViewById(R.id.fs_search_t);
		sButton = (Button) findViewById(R.id.fs_search_b);
        sButton.setOnClickListener(this);
        addButton = (Button) findViewById(R.id.fs_add_food);
        addButton.setOnClickListener(this);
        ((TextView)findViewById(R.id.fs_search_t)).clearFocus();
        
        Spinner gSpinner = (Spinner) this.findViewById(R.id.fs_foodgroup);
        ArrayAdapter<CharSequence> gAdapter = ArrayAdapter.createFromResource(this, R.array.food_group, android.R.layout.simple_spinner_item);
        gAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        gSpinner.setAdapter(gAdapter);
        
        lsComposer = (AmazingListView) findViewById(R.id.fs_list);    
        lsComposer.setTextFilterEnabled(true);
		lsComposer.setDivider( null );
		lsComposer.setDividerHeight(1); 
        lsComposer.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				TextView foodId = (TextView) view.findViewById(R.id.fs_food_id);
				Intent intent = null;	
				if(Constant.FA_FOOD_LOG.equalsIgnoreCase(fActivity) || Constant.FA_HOME.equalsIgnoreCase(fActivity)){
					intent = new Intent(FoodAddActivity.this,FoodAddDetailActivity.class);
				}else if(Constant.FA_FOOD_DESIGN.equalsIgnoreCase(fActivity)){
					intent = new Intent(FoodAddActivity.this,PlanAddDetailActivity.class);
					intent.putExtra(Constant.C_DIET_ID,did);
				}else{
					intent = new Intent(FoodAddActivity.this,ShowFoodDetail.class);
				}
				intent.putExtra("foodId", foodId.getText().toString());
				startActivity(intent);
			}
		});
	}	
	
	
	class SectionComposerAdapter extends AmazingAdapter {
		private AsyncTask<Integer, Void, Pair<Boolean, List<Food>>> backgroundTask;
		private List<Food> list = new ArrayList<Food>();	
		
		public void reset() {
			if (backgroundTask != null) backgroundTask.cancel(false);
			
			list = fManager.getFoods(null,fText.getText().toString(), 1).second;
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Food getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		protected void onNextPageRequested(int page) {			
			if (backgroundTask != null) {
				backgroundTask.cancel(false);
			}
			
			backgroundTask = new AsyncTask<Integer, Void, Pair<Boolean, List<Food>>>() {
				@Override
				protected Pair<Boolean, List<Food>> doInBackground(Integer... params) {
					int page = params[0];					
					return fManager.getFoods(null, fText.getText().toString(), page);
				}
				
				@Override
				protected void onPostExecute(Pair<Boolean, List<Food>> result) {
					if (isCancelled()) return; 
					
					list.addAll(result.second);
					nextPage();
					notifyDataSetChanged();
					
					if (result.first) {
						notifyMayHaveMorePages();
					} else {
						notifyNoMorePages();
					}
				};
			}.execute(page);
		}

		@Override
		public View getAmazingView(int position, View convertView, ViewGroup parent) {
			View res = convertView;
			if (res == null) res = getLayoutInflater().inflate(R.layout.food_search_item, null);
			TextView foodName = (TextView) res.findViewById(R.id.fs_food_name);
			TextView foodGroup = (TextView) res.findViewById(R.id.fs_food_group);
			TextView foodEnergy = (TextView) res.findViewById(R.id.fs_food_energy);
			TextView foodId = (TextView) res.findViewById(R.id.fs_food_id);
			
			Food item = getItem(position);
			foodName.setText(StringUtil.cutString(item.getFoodName(),40));
			foodGroup.setText(item.getFoodGroup());
			foodEnergy.setText(item.getEnergy());
			foodId.setText(item.getId());
			return res;
		}

		@Override
		protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
		}

		@Override
		public void configurePinnedHeader(View header, int position, int alpha) {
		}

		@Override
		public int getPositionForSection(int section) {
			return 0;
		}

		@Override
		public int getSectionForPosition(int position) {
			return 0;
		}

		@Override
		public Object[] getSections() {
			return null;
		}
		
		
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.fs_search_b){
			this.showDialog(0);
			SearchThread thread = new SearchThread();
			thread.start();
		}else if(v.getId() == R.id.fs_add_food){
			Intent intent = new Intent(FoodAddActivity.this, AddCustomFoodActivity.class);	
			startActivity(intent);
		}
	}
		
	private void displaySearchResults(){
		adapter = new SectionComposerAdapter();
		lsComposer.setLoadingView(getLayoutInflater().inflate(R.layout.loading_view, null));
		lsComposer.setDivider( null );
		lsComposer.setDividerHeight(1); 
		lsComposer.setAdapter(adapter);
		refreshList();
	}
	
	public void refreshList(){
		adapter.reset();
		
		if(adapter.getCount()==0){
			lsComposer.setVisibility(View.GONE);
		}else{
			lsComposer.setVisibility(View.VISIBLE);
			adapter.resetPage();
			adapter.notifyMayHaveMorePages();
		}		
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id){
			case 0:
				progressDialog = new ProgressDialog(this);
				progressDialog.setTitle("Searching. Please wait...");
				progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				return progressDialog;			
		}
		
		return null;		
	}
	
	private class SearchThread extends Thread {
        @Override
        public void run() {  
            handler.sendEmptyMessage(0);
        }

        private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                displaySearchResults();
                progressDialog.dismiss();
            }
        };
    }
}
